package com.ghsc.ghxc.jsb.ui.main

import android.Manifest
import android.os.Process
import android.text.TextUtils
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alivc.auicommon.common.roombase.Const
import com.aliyun.aliinteraction.uikit.uibase.util.LastLiveSp
import com.aliyun.auiappserver.AppServerTokenManager
import com.cn.appcore.adapter.CustomFragmentStateAdapter
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.ApkUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.cn.appcore.utils.TimeUtils
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.ActivityMainBinding
import com.ghsc.ghxc.jsb.ui.bean.VersionDataBean
import com.ghsc.ghxc.jsb.ui.home.HomeFragment
import com.ghsc.ghxc.jsb.ui.live.TabLiveVideoActivity
import com.ghsc.ghxc.jsb.ui.main.view.NoticePopView
import com.ghsc.ghxc.jsb.ui.mall.MallFragment
import com.ghsc.ghxc.jsb.ui.message.MessageFragment
import com.ghsc.ghxc.jsb.ui.message.view.RouterUtils
import com.ghsc.ghxc.jsb.ui.my.MyFragment
import com.ghsc.ghxc.jsb.view.VersionPopView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.auth.LoginInfo
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.yunxin.kit.chatkit.model.ConversationInfo
import com.netease.yunxin.kit.chatkit.repo.ConversationObserverRepo
import com.netease.yunxin.kit.chatkit.repo.ConversationRepo
import com.netease.yunxin.kit.corekit.im.IMKitClient
import com.netease.yunxin.kit.corekit.im.login.LoginCallback
import com.netease.yunxin.kit.corekit.im.model.EventObserver
import com.netease.yunxin.kit.corekit.im.provider.FetchCallback
import com.permissionx.guolindev.PermissionX

/**
 * 项目：ScanCodePic
 * 包名：com.xlcn.scan.ui.main
 * 类名：MainActivity
 * 创建时间：2024/4/11 17:02
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class MainActivity : BaseVMActivity<MainViewModel, ActivityMainBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_main
    }

    override fun attachVMClass(): Class<MainViewModel>? {
        return MainViewModel::class.java
    }


    private var mFragmentAdapter: CustomFragmentStateAdapter<Fragment>? = null
    private var selectIndex = 0
    var userRid: String by Preference(HttpConstant.USER_RID, "")
    var userId: String by Preference(HttpConstant.USER_ID, "")

    /** 检查是否缓冲id 没有就重新登录 **/
    private fun  checkIsLogin() {
        var uid = UserManager.getUserId()
        if (TextUtils.isEmpty(userRid) || TextUtils.isEmpty(userId) || TextUtils.isEmpty(uid)) {
            showToast(CustKey.IN_AGAIN_MSG)
            LoginHelper.startLoginPage(this)
        }
    }


    override fun onResume() {
        super.onResume()
        if (selectIndex==0 || selectIndex==3){
            mViewModel.onSysConfigMethod("")
        }
        checkIsLogin()
        isShowNoticeData()
    }
    /** 显示公告弹窗 **/
    private fun showNoticeData(content:String){
        if (!TextUtils.isEmpty(content)){
//            UserManager.setAppNotice(TimeUtils.getNowDate().toString())
            XPopup.Builder(this@MainActivity)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                .customHostLifecycle(lifecycle)
                .dismissOnTouchOutside(false)
                .asCustom(
                    NoticePopView(this@MainActivity,"公告",content)
                )
                .show()
        }

    }

    override fun initView() {




        var listFragment = arrayListOf<Fragment>()
        listFragment.add(HomeFragment())
//            listFragment.add(LiveFragment())
        listFragment.add(MallFragment())
        listFragment.add(MessageFragment())
        listFragment.add(MyFragment())
        mFragmentAdapter = CustomFragmentStateAdapter<Fragment>(this).apply {
            setNewData(listFragment)
        }
        binding.myViewPage.adapter = mFragmentAdapter
        binding.myViewPage.offscreenPageLimit =
            mFragmentAdapter?.itemCount ?: ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
        binding.myViewPage.isUserInputEnabled = false
        UserManager.setIsFirst("1")
        //清除阿里直播缓存
        Const.setUserId("")
        LastLiveSp.INSTANCE.lastLiveId = ""
        LastLiveSp.INSTANCE.lastLiveAnchorId = ""
        AppServerTokenManager.setAppServerToken("")
        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
                    rxBusBean.id == CustSignKey.IM_NOT_MSG && rxBusBean.sign == CustSignKey.IM_NOT_MSG -> {
                        //云信系统通知
                        val bId= rxBusBean.anyBean.toString()
                        loge("message_id="+bId)
                        val map: HashMap<String, Any> = HashMap()
                        map["message_id"] =bId
                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onYxMessageConvertMethod(it1) }
                    }
                }
            }

        mViewModel.onUserInfoMethod()

    }

    override fun initData() {
        super.initData()
        setSelect(0)
    }
    private fun setSelect(it: Int) {
        selectIndex = it
        //这里判断是确保未被拦截
        if (selectIndex == it) {
            showFragment(it)
            tabInitView()
            when (it) {
                0 -> {
                    binding.imgPage.setImageResource(R.drawable.ic_main_home_selected)
                    binding.tvPage.setTextColor(getCompatColor(R.color.main_color))

                }
                1 -> {
                    binding.imgTactics.setImageResource(R.drawable.ic_main_red_packet_mall_selected)
                    binding.tvTactics.setTextColor(getCompatColor(R.color.main_color))
                }
                2 -> {
                    binding.imgHistory.setImageResource(R.drawable.ic_main_material_selected)
                    binding.tvHistory.setTextColor(getCompatColor(R.color.main_color))
                }
                3 -> {
                    binding.imgMy.setImageResource(R.drawable.ic_main_mine_selected)
                    binding.tvMy.setTextColor(getCompatColor(R.color.main_color))
                }
                else -> {}
            }

        }
    }
    //切换
    private fun showFragment(index: Int) {
        binding.myViewPage.setCurrentItem(index, false)
    }

    //默认状态
    private  fun tabInitView(){
        binding.tvPage.text = "首页"
        binding.tvTactics.text = "资讯"
        binding.tvHistory.text = "消息"
        binding.tvMy.text = "我的"
        binding.imgPage.setImageResource(R.drawable.ic_main_home_unselected)
        binding.imgTactics.setImageResource(R.drawable.ic_main_red_packet_mall_unselected)
        binding.imgHistory.setImageResource(R.drawable.ic_main_material_unselected)
        binding.imgMy.setImageResource(R.drawable.ic_main_mine_unselected)

        binding.tvPage.setTextColor(getCompatColor(R.color.color_4d4d4d))
        binding.tvTactics.setTextColor(getCompatColor(R.color.color_4d4d4d))
        binding.tvHistory.setTextColor(getCompatColor(R.color.color_4d4d4d))
        binding.tvMy.setTextColor(getCompatColor(R.color.color_4d4d4d))
    }


    override fun initClickListener() {
        super.initClickListener()
        binding.run {
            llBtnPage.setSingleClickListener {
                mImmersionBar!!.statusBarDarkFont(false).init()
                setSelect(0)
            }
            llBtnTactics.setSingleClickListener {
//                showToast("即将上线,敬请期待")
                mImmersionBar!!.statusBarDarkFont(true).init()
                setSelect(1)
            }
            llBtnHistory.setSingleClickListener {
                mImmersionBar!!.statusBarDarkFont(false).init()
                setSelect(2)
            }
            llBtnMy.setSingleClickListener {
                mImmersionBar!!.statusBarDarkFont(true).init()
                setSelect(3)
            }
            llBtnLive.setSingleClickListener {
                startActivity(TabLiveVideoActivity().javaClass)
//                if ( !TextUtils.isEmpty(AppServerTokenManager.getAppServerToken()) && !TextUtils.isEmpty(Const.getUserId()) &&
//                    Const.getUserId() == userId) {
////                    startActivity(LiveListActivity().javaClass)
//                    startActivity(TabLiveVideoActivity().javaClass)
//                } else {
//                    showLoading()
//                    //todo 直播请求自己的接口 登录 login 参数 request
//                    AppServerTokenManager.login(userId, userId,
//                        object : InteractionCallback<Void?> {
//                            override fun onSuccess(data: Void?) {
//                                loge("直播登录=")
//                                dismissLoading()
//                                Const.setUserId(userId)
////                                    UserHelper.storeUserId(UserManager.getUserId())
//                                if (!TextUtils.isEmpty(Const.getUserId())){
//                                    startActivity(LiveListActivity().javaClass)
//                                }
//                            }
//
//                            override fun onError(interactionError: InteractionError?) {
//                                dismissLoading()
//                                showToast("服务器出错...")
//                            }
//                        })
//                }
            }
        }
    }


    private var exitTime: Long = 0 //标记退出时间。

    /**
     * 退出
     */
    override fun onBackPressed() {
        val currentTime = System.currentTimeMillis()
        if (currentTime - exitTime < 2000) {
            super.onBackPressed()
            finish()
            Process.killProcess(Process.myPid())
            Runtime.getRuntime().gc()
        } else {
            showToast("再按一次退出程序")
            exitTime = currentTime
        }
    }



    /** 是否显示公告弹窗 **/
    private  fun isShowNoticeData(){
        //公告
        mViewModel.onNotifyMethod("")

    }



    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@MainActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@MainActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onUserInfoData.observe(this@MainActivity) {
                var userId: String by Preference(HttpConstant.USER_ID, "")
                //缓存个人信息
                UserManager.saveUserInfo(it.data.data)
                UserManager.setUserName(it.data.data.nickname)
                UserManager.setUserHead(it.data.data.headimg)
                UserManager.setUserId(userId)

                //获取云信token
                val map: HashMap<String, Any> = HashMap()
                map["ifupd"]=1
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGetTokenMethod(it1) }

            }
            onGetTokenData.observe(this@MainActivity) {
                ///登录云信IM
                 loge("云信的 id="+userId)
                loge("云信的 token="+it.data.data.token)
                val loginInfo = LoginInfo.LoginInfoBuilder.loginInfoDefault(userId, it.data.data.token)
                    .withAppKey(if (CustKey.APP_EN_MENT==0) CustKey.IM_YUN_XIN_KEY else CustKey.IM_YUN_XIN_KEY_RS)
                    .build()
                IMKitClient.loginIM(loginInfo, object : LoginCallback<LoginInfo> {
                    override fun onError(errorCode: Int, errorMsg: String) {
                        loge("云信登录失败==" + errorCode + "==" + errorMsg)
//                        mViewModel.onGetRyToKenMethod("")

                    }

                    override fun onSuccess(data: LoginInfo?) {
                        loge("云信登录成功==")
//                        RouterUtils.setFriendsUserInfo()
                        RouterUtils.setUserInfo(UserManager.getUserName(),UserManager.getUserHead())
                        val countAll=  NIMClient.getService(MsgService::class.java).totalUnreadCount
                        if(countAll>0){
                            if(countAll>=99){
                                binding.tvCount.visibility= View.VISIBLE
                                binding.tvCountNum.visibility= View.GONE
                            }else {
                                binding.tvCount.visibility= View.GONE
                                binding.tvCountNum.visibility= View.VISIBLE
                                binding.tvCountNum.text=countAll.toString()
                            }
                        }else{
                            binding.tvCount.visibility= View.GONE
                            binding.tvCountNum.visibility= View.GONE
                        }
                        initIMCount()
                    }

                })
            }
            onNotifyData.observe(this@MainActivity){
                var notStr =UserManager.getAppNotice()
                if(!TextUtils.isEmpty(it.data.data.cfg_value)){
                    if(!TextUtils.isEmpty(notStr)){
                        if(notStr != it.data.data.cfg_value){
                            showNoticeData(it.data.data.cfg_value)
                            UserManager.setAppNotice(it.data.data.cfg_value)
                        }
                    }else{
                        UserManager.setAppNotice(it.data.data.cfg_value)
                        showNoticeData(it.data.data.cfg_value)
                    }
                }
            }
            onSysConfigData.observe(this@MainActivity) {
                //保存配置
                UserManager.saveConfig(it)
                //版本更新
                var sysConfigResultData = it.getSysConfigBean( CustKey.configK5 )
                if(sysConfigResultData!=null)
                    if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
                        val bean =GsonUtil.GsonToJsonClass(sysConfigResultData.cfg_value, VersionDataBean::class.java)
                        val versionName  = ApkUtil.getVersionName()
                        //和最小的版本对比  小于后台的最小，强制更新
                        val versionSign = ApkUtil.compareVersion(versionName, bean.version)

                        if(versionSign<0){
                            if (bean.url.contains(".apk")){
                                var appVersionTime = UserManager.getAppVersionTime()
                                if (!TextUtils.isEmpty(appVersionTime)){
                                    if(appVersionTime != TimeUtils.getNowDate()){
                                        isPermissionX(bean)
                                    }
                                }else{
                                    //等于空 说明今儿没有弹过
                                    isPermissionX(bean)
                                }
                            }
                        }
                    }
            }
        }
    }


    ///云信Im未读
    private fun initIMCount(){
        ConversationObserverRepo.registerSessionChangedObserver(object :
            EventObserver<List<ConversationInfo>>() {
            override fun onEvent(event: List<ConversationInfo>?) {
//                                val numCount=  NIMClient.getService(MsgService::class.java).totalUnreadCount
//                                loge("云信未读111=" +numCount)
                ConversationRepo.getMsgUnreadCountAsync(
                    object : FetchCallback<Int> {
                        override fun onSuccess(param: Int?) {
                            val countAll: Int = param!!
                            if (countAll > 0) {
                                if (countAll >= 99) {
                                    binding.tvCount.visibility = View.VISIBLE
                                    binding.tvCountNum.visibility = View.GONE
                                } else {
                                    binding.tvCount.visibility = View.GONE
                                    binding.tvCountNum.visibility = View.VISIBLE
                                    binding.tvCountNum.text = countAll.toString()
                                }
                            } else {
                                binding.tvCount.visibility = View.GONE
                                binding.tvCountNum.visibility = View.GONE
                            }
                        }

                        override fun onFailed(code: Int) {
                        }

                        override fun onException(exception: Throwable?) {
                        }
                    })
//


            }

        })
    }


    private  fun isPermissionX(bean : VersionDataBean){
        //和最小的版本对比  小于后台的最小，强制更新
        if (!TextUtils.isEmpty(bean.version) || !TextUtils.isEmpty(bean.url) ){
            PermissionX.init(this@MainActivity)
                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request { allGranted, _, _ ->
                    if (allGranted) {
                        upApk(bean)
                    } else {
                        showToast("需开启权限才能进行操作")
                    }
                }
        }
    }
    private fun upApk(apkBean : VersionDataBean){
        XPopup.Builder(this@MainActivity)
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .customHostLifecycle(lifecycle)
            .dismissOnTouchOutside(false)
            .hasShadowBg(true)
            .enableDrag(false)
            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
            //这个属性必须加，不然GiftFragment出问题
            .isViewMode(true)
            .asCustom(VersionPopView(this@MainActivity, apkBean).apply {
                setOnCloseDismiss {
                    UserManager.setAppVersionTime(TimeUtils.getNowDate().toString())
                }
            })
            .show()
    }
}